package machine

import (
	"GraduationProject/public/db"
	"GraduationProject/public/models"
	"GraduationProject/webserver/controllers/util"
	"github.com/gin-gonic/gin"
)

// todo: 获取机器信息 (分页)
func GetMachines(ctx *gin.Context) {
	if _, err := util.AdminFilter(ctx); err != nil {
		return
	}

	offset := ctx.PostForm("offset")
	limit := ctx.PostForm("limit")

	var machines []models.Machine
	var count int
	db.DB.Model(&models.Machine{}).Count(&count)
	db.DB.Offset(offset).Limit(limit).Find(&machines)
	//util.SuccessResponse(ctx, "machines", machines)
	ctx.JSON(200, gin.H{
		"status":   10000,
		"message":  "success",
		"machines": machines,
		"count":    count,
	})
}

// todo: 修改机器状态
func SetMachineStatus(ctx *gin.Context) {
	if _, err := util.AdminFilter(ctx); err != nil {
		return
	}

	machineID, err := util.PostFormInt(ctx, "id")
	if err != nil {
		return
	}
	status, err := util.PostFormInt(ctx, "status")
	if err != nil {
		return
	}

	if status != models.MachineStatusRunning &&
		status != models.MachineStatusStopped {
		util.FailedResponse(ctx, 10999, "无此机器状态")
		return
	}

	if db.DB.Model(&models.Machine{}).
		Where("`id` = ?", machineID).
		Update("status", status).RowsAffected == 0 {
		util.FailedResponse(ctx, 19999, "未知错误")
		return
	}

	util.SuccessResponse(ctx)
}
